﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HttpServer;
using HttpServer.Modules;
using HttpServer.Resources;
using HttpServer.BodyDecoders;
using System.Net;
using HttpListener = HttpServer.HttpListener;
using System.IO;
using System.Net.Sockets;

namespace HttpFiler
{
    public partial class MainForm : Form
    {
        private Server server = new Server();
        private VirtualFileResources vfiles = new VirtualFileResources();
        public MainForm()
        {
            InitializeComponent();
        }

        
        private void listFiles_DragDrop(object sender, DragEventArgs e)
        {
            foreach (string filePath in (string[])e.Data.GetData(DataFormats.FileDrop))
            {
                if (File.Exists(filePath))
                {
                    FileInfo fi = new FileInfo(filePath);
                    if (!isFilenameShared(fi.Name))
                    {
                        listFiles.Items.Add(new ListViewItem(new string[] { fi.Name, filePath }));
                        vfiles.Add(fi.Name, filePath);
                    }

                }
                else if (Directory.Exists(filePath))
                {

                }
                
            }
        }

        private bool isFilenameShared(string filename)
        {
            foreach (ListViewItem lvi in listFiles.Items)
            {
                if (string.Compare(lvi.Text, filename, true) == 0)
                    return true;
            }
            return false;
        }

        private void listFiles_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
            {
                e.Effect = DragDropEffects.All;
            }
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

            Random rnd = new Random();
            int port = rnd.Next(1024, 65000);
            txtPort.Text = port.ToString();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                int port = getPortNumber();

                StartHttpServer(port);

                ShowUrls();

                btnStart.Enabled = false;
                txtPort.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ShowUrls()
        {
            string urls = string.Empty;
            IPAddress[] ipAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in ipAddresses)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    urls += "http://" + ip.ToString() + ":" + txtPort.Text + "/, ";
            }

            lblUrls.Text = urls.TrimEnd(", ".ToCharArray());
        }

        private void StartHttpServer(int port)
        {
            VirtualFileModule module = new VirtualFileModule();

            module.Resources.Add(vfiles);
            server.Add(module);
            server.Add(new MultiPartDecoder());
            server.Add(HttpListener.Create(IPAddress.Any, port));

            server.Start(5);
        }

        private int getPortNumber()
        {
            int port = -1;
            if (int.TryParse(txtPort.Text, out port))
            {
                if (port > 0 && port < 65535)
                    return port;
            }

            throw new Exception("Port must be a number between 1 and 65534");
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (MessageBox.Show("Do you want to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
            {
                e.Cancel = true;
            }
            base.OnClosing(e);
        }

        private void listFiles_KeyPress(object sender, KeyPressEventArgs e)
        {
            //e.
            //if (e.KeyChar == Keys.Delete
        }

        private void listFiles_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                foreach (ListViewItem lvi in listFiles.SelectedItems)
                {
                    listFiles.Items.Remove(lvi);
                    vfiles.Remove(lvi.Text);
                }
            }
        }

    }
}
